package com.hotel.front;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.gson.Gson;
import com.hotel.BL.AgencyLogic;
import com.hotel.BL.CreditCardLogic;
import com.hotel.BL.GuestLogic;
import com.hotel.BL.PopupLogic;
import com.hotel.BL.ReservationLogic;
import com.hotel.BL.RoomLogic;
import com.hotel.BL.RoomTypeLogic;






import data.Agency;
import data.Charge;
import data.CleaningStatus;
import data.CreditCard;
import data.General;
import data.Guest;
import data.Package;
import data.PackageByDate;
import data.Payment;
import data.Reservation;
import data.ReservationStatus;
import data.Room;
import data.RoomType;
import data.SubReservation;
import data.passingData.LoadPopupShowData;


@SuppressWarnings("serial")
public class PopupService extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			String doClass = req.getParameter("doClass");
			if (doClass.equals("loadSalutation")) {
				LoadSalutation(req, resp);
			} else if (doClass.equals("loadPackage")) {
				LoadPackage(req, resp);
			} else if (doClass.equals("loadOccupancy")) {
				LoadOccupancy(req, resp);
			} else if (doClass.equals("loadRoom")) {
				LoadRoom(req, resp);
			} else if (doClass.equals("loadGeneral")) {
				LoadGeneral(req, resp);
			} else if (doClass.equals("loadReservation")) {
				LoadReservation(req, resp);
			} else if (doClass.equals("loadPriceRate")) {
				LoadPriceRate(req, resp);
			} else if (doClass.equals("loadGuest")) {
				LoadGuest(req, resp);
			} else if (doClass.equals("loadRoomtypeName")) {
				LoadRoomtypeName(req, resp);
			} else if (doClass.equals("loadResvStatus")) {
				LoadResvStatus(req, resp);
			}else if (doClass.equals("loadCleaningStatus")) {
				LoadCleaningStatus(req, resp);
			} else if (doClass.equals("loadAllRoomtype")) {
				LoadAllRoomtype(req, resp);
			} else if (doClass.equals("loadRoomG")) {
				LoadRoomG(req, resp);
			} else if (doClass.equals("loadRoomName")) {
				LoadRoomName(req, resp);
			} else if (doClass.equals("loadPopShowData")) {
				LoadPopShowData(req, resp);
			} else if (doClass.equals("loadCreditCard")) {
				LoadCreditCard(req, resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void LoadResvStatus(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		List<ReservationStatus> obj = new PopupLogic(req,resp)
				.LoadReservationStatus(hotelId);

		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));

	}

	private void LoadCleaningStatus(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		List<CleaningStatus> obj = new PopupLogic(req,resp).LoadCleaningStatus(hotelId);

		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));

	}

	private void LoadSalutation(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, JSONException, ServletException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		Object obj = new PopupLogic(req,resp).LoadSalutation(hotelId);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}

	private void LoadPackage(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, JSONException, ServletException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");

		List<Package> packages = new PopupLogic(req,resp).LoadPackage(hotelId);
		
		for(Package p : packages)
		{
			p.getPackagepriceList();
		}

		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(packages));
	}

	private void LoadOccupancy(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, JSONException, ServletException {
		String roomtype = req.getParameter("roomtype");
		long roomtypeId = Long.parseLong(roomtype);
		RoomType obj = new PopupLogic(req,resp).LoadOccupancy(roomtypeId);

		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}

	private void LoadRoom(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, JSONException, ServletException, ParseException {
		HttpSession session = req.getSession(true);
		long hotelId = (Long) session.getAttribute("hotelId");
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		Date date = formatter.parse(req.getParameter("date"));
		long span = Long.parseLong(req.getParameter("span"));
		long roomtype = Long.parseLong(req.getParameter("roomtype"));
		List<SubReservation> subRsv = new ReservationLogic(req,resp).GetUsedRoomWithinDateWithAssign(hotelId,
				date,span, roomtype);
		List<Room> obj = new PopupLogic(req,resp).LoadRoomWithCache(hotelId, roomtype);
		for(SubReservation s: subRsv)
		{
			for(int i=0;i<obj.size();i++)
				if(obj.get(i).getId() == s.getRoom().getId())
				{
					obj.remove(i);
					break;
				}
		}

		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj.size()));
	}

	private void LoadGeneral(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, JSONException,
			ServletException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) (session.getAttribute("hotelId"));
		General g = new PopupLogic(req,resp).LoadGeneral(hotelId);
		g.getDateFormat();
		g.getDefaultCurrency();

		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(g));
	}

	private void LoadReservation(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, JSONException,
			ServletException {
		long resId = Long.parseLong(req.getParameter("resId"));
		Object obj = new ReservationLogic(req,resp).GetReservation(resId);

		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}

	private void LoadPriceRate(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, JSONException, ServletException {
		long priceRateId = Long.parseLong(req.getParameter("priceRateId"));
		Object obj = new PopupLogic(req,resp).LoadPriceRate(priceRateId);

		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}

	private void LoadGuest(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, JSONException, ServletException {
		long guestId = Long.parseLong(req.getParameter("guestId"));
		Guest obj = null;
		if(guestId!=0){
			 obj = new GuestLogic(req,resp).GetGuest(guestId);
		}
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}

	private void LoadRoomtypeName(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, JSONException,
			ServletException, ParseException {
		String roomtypeId = req.getParameter("roomtypeId");
		long id = Long.parseLong(roomtypeId);

		RoomType obj = new RoomTypeLogic(req,resp).GetRoomType(id);
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj.getShortName()));
	}

	private void LoadAllRoomtype(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, JSONException,
			ServletException, ParseException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) (session.getAttribute("hotelId"));
		List<RoomType> obj = new RoomTypeLogic(req,resp).GetAllRoomType(hotelId);
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));

	}

	private void LoadRoomG(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, JSONException, ServletException, ParseException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) (session.getAttribute("hotelId"));

		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd",
				Locale.ENGLISH);
		Date date = formatter.parse(req.getParameter("date"));
		long span = Long.parseLong(req.getParameter("span"));
		long roomtype = Long.parseLong(req.getParameter("roomtype"));
		long except = -1;
		if(req.getParameter("except")!= null && req.getParameter("except") != "")
			except = Long.parseLong(req.getParameter("except"));

		List<SubReservation> subRsv = new ReservationLogic(req,resp).GetUsedRoomWithinDateWithAssign(hotelId,
				date,span, roomtype);
		List<Room> obj = new PopupLogic(req,resp).LoadRoomWithCache(hotelId, roomtype);

		for(SubReservation s: subRsv)
		{
			for(int i=0;i<obj.size();i++)
				if(except > 0 && (s.getId() == except || s.getParentId() == except))
					continue;
				else if(obj.get(i).getId() == s.getRoom().getId())
				{
					obj.remove(i);
					break;
				}
		}
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}

	private void LoadRoomName(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, JSONException, ServletException, ParseException {
		String roomId = req.getParameter("roomId");
		long id = Long.parseLong(roomId);

		Room obj = new RoomLogic(req,resp).GetRoom(id);
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj.getRoomName()));
	}

	private void LoadPopShowData(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, JSONException,
			ServletException, ParseException {
		HttpSession session = req.getSession(true);
		@SuppressWarnings("unused")
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) (session.getAttribute("hotelId"));

		long resId = Long.parseLong(req.getParameter("resId"));
		double charge = 0.0;
		double pay = 0.0;
		double chargeGroup = 0.0;
		double payGroup = 0.0;
		LoadPopupShowData popup = new LoadPopupShowData();

		Reservation resv = new ReservationLogic(req,resp).GetReservation(resId);
		popup.setAdult(resv.getAdult());
		popup.setDate(resv.getDate());
		popup.setChild(resv.getChild());
		popup.setSpan(resv.getSpan());
		popup.setGroupId(resv.getGroupIdString());
		if(resv.getAgencyIdString()!=  null&&!resv.getAgencyIdString().equals("0")){
			Agency agency = new AgencyLogic(req,resp).GetAgency(Long.parseLong(resv
					.getAgencyIdString()));
			popup.setAgency(String.valueOf(agency.getAgency()));
		}else{
			popup.setAgency("-");
		}
		if(resv.getGuestString()!=null&&!resv.getGuestString().equals("0")){
			Guest guest = resv.getGuest();
			popup.setEmail(guest.getMail());
			popup.setGuestId(String.valueOf(guest.getId()));
			popup.setGuestName(guest.getFirstName() + " " + guest.getLastName());
			popup.setTel(guest.getPhone());
			popup.setAddress(guest.getAddressLine1() + "" + guest.getAddressLine2());
		}
		if(resv.getGroupIdNumber() != 0 && resv.getGroupId().getGuest()!=null){
			
			Guest owner = resv.getGroupId().getGuest();
			popup.setOwnerGroupId(String.valueOf(owner.getId()));
			popup.setOwnerGroupName(owner.getFirstName() + " "
					+ owner.getLastName());
		}else{

			popup.setOwnerGroupId("");
			popup.setOwnerGroupName("");
		}
		
		List<PackageByDate> pbd = resv.getPackageByDate();
		String packageName = "";
		for(int x=0;x<pbd.size();x++){
			packageName += pbd.get(x).getPackages().getName()+",";
		}
		//packageName.substring(0, packageName.length()-1)
		popup.setPackageName(packageName.substring(0, packageName.length()-1));

		List<SubReservation> subResv = resv.getSubReservationList();
		if(subResv.size() == 0)
		{
			Room r = resv.getRoom();
			popup.setRoomName(r.getRoomName());
	
			RoomType rt = resv.getRoomType();
			popup.setRoomtypeName(rt.getShortName());
		}
		else
		{
			List<List<Room>> roomList = new ArrayList<List<Room>>();
			for(SubReservation sub : subResv)
			{
				if(roomList == null || roomList.size() == 0)
				{
					List<Room> l = new ArrayList<Room>();
					l.add(sub.getRoom());
					roomList.add(l);
					continue;
				}
				boolean foundList = false;
				boolean duplicate = false;
				for(List<Room> rooms : roomList)
					if(rooms.get(0).getRoomtype().getId() == sub.getRoomType().getId())
					{
						duplicate = false;
						for(Room r : rooms)
							if(r.getId() == sub.getRoom().getId())
								duplicate = true;
						if(!duplicate)
						{
							rooms.add(sub.getRoom());
						}
						foundList = true;
					}
				if(!foundList)
				{
					List<Room> l = new ArrayList<Room>();
					l.add(sub.getRoom());
					roomList.add(l);
				}
			}
			
			String roomTypeString = "";
			String roomString = "";
			for(List<Room> list : roomList)
			{
				roomTypeString += list.get(0).getRoomtype().getShortName() + "(";
				for(Room r : list)
				{
					roomTypeString += r.getRoomName() + ",";
					roomString += r.getRoomName() + ",";
				}
				roomTypeString = roomTypeString.substring(0, roomTypeString.length()-1);
				roomTypeString += "), ";
			}
			roomTypeString = roomTypeString.substring(0, roomTypeString.length()-2);
			roomString = roomString.substring(0, roomString.length()-1);
			popup.setRoomtypeName(roomTypeString);
			popup.setRoomName(roomString);
		}

		//TODO: Include Other Charge
		List<Charge> cList =  resv.getChargeList();
		if(cList != null){		
			for(int i =0;i<cList.size();i++){
				charge += cList.get(i).getChargeAmount();
			}
		}
		if(resv.getOtherChargeString() != null&&!resv.getOtherChargeString().equals("")){
		List<Charge> ocList =  resv.getOtherChargeList();
		if(cList != null){		
			for(int i =0;i<ocList.size();i++){
				charge += ocList.get(i).getChargeAmount();
			}
		}
		}
		popup.setTotal(charge);
		
		
		List<Payment> pList = resv.getPaymentList();
		
		if(pList != null){	
			for(int i =0;i<pList.size();i++){
				pay += pList.get(i).getAmount();
			}
			popup.setPay(pay);
		}else{
			popup.setPay(0.0);
		}
		
		popup.setBalance(charge - pay);

		if(!resv.getGroupIdString().equals("0")){
			if(resv.getGroupId().getChargeListString()!=null){
				List<Charge> cgList = resv.getGroupId().getChargeList();
				if(cgList != null&&!cgList.isEmpty()){
					for(int i =0;i<cgList.size();i++){
						chargeGroup += cgList.get(i).getChargeAmount();
					}
				}
			}
			List<Reservation> rList = resv.getGroupId().getListResv();
			for(int i = 0;i<rList.size();i++){
				if(rList.get(i).getChargeList() != null){
					List<Charge> cList1 = rList.get(i).getChargeList();
					for(int k = 0;k<cList1.size();k++){
						chargeGroup += cList1.get(k).getChargeAmount();
					}
				}
				
			}
			popup.setTotalGroup(chargeGroup);
			List<Payment> pgList = resv.getGroupId().getPaymentList();
			if(pgList != null){
				if(pgList.size() != 0 ){
					for(int i =0;i<pgList.size();i++){
						payGroup += pgList.get(i).getAmount();
					}
					popup.setPayGroup(payGroup);
				}else{
					popup.setPayGroup(0.0);
				}
			}else{
				popup.setPayGroup(0.0);
			}
			popup.setBalanceGroup(chargeGroup - payGroup);
		}else{
			popup.setPayGroup(0.0);
			popup.setTotalGroup(0.0);
			popup.setBalanceGroup(0.0);
		}
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(popup));
	}
	
	private void LoadCreditCard(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String guestId = req.getParameter("guestId");
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
		GuestLogic guestLogic = new GuestLogic(req,resp);
		CreditCardLogic creditCardLogic = new CreditCardLogic(req,resp);
		if(guestLogic.getCreditCard(guestId) != null){
			List<CreditCard> g = guestLogic.getCreditCard(guestId);
			for(CreditCard c: g) {
				String CCN = creditCardLogic.enCodeCreditCardNumber(c.getCardNumber());
				HashMap<String,Object> hash = com.Util.toHashmap(c); 
				hash.remove("key");
				hash.remove("Address");
				hash.remove("City");
				hash.remove("Country");
				hash.remove("Zipcode");
				hash.remove("State");
				hash.remove("CVC");
				hash.remove("CardNumber");
				hash.remove("status");
				hash.remove("hotelId");
				hash.put("CardNumber",CCN);
				hash.put("id",c.getId());
				list.add(hash); 
			}
		}else{
			list = null;
		}
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(list));
	}
	
}
